package cn.shuangliang.contract.web;

import cn.shuangliang.contract.model.Contract;
import cn.shuangliang.contract.service.ContractService;
import cn.shuangliang.contract.vo.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 返回String,表示转发地址。。。
 * return MovelAndView:综合的对象，包括数据和转发的视图地址
 */
//合同
@Controller
@RequestMapping("contract")
public class ContractController {
    @Autowired
    private ContractService contractService;

    //1：一步绑定到对象
    //2:日期的问题  ：一个注解
    //3：中文问题：一个过滤器
    //4:处理器如何和集成好的bean结合。。。
    //分页
    @GetMapping("search")
    public ModelAndView paging(@RequestParam(name = "page",defaultValue = "1") int pageNo){
        Page<Contract> search = contractService.search(pageNo, null, null, null, null);
       // InternalResourceViewResolver v=null;
//        v.setPrefix();
//        v.setSuffix(;);
        ModelAndView mv=new ModelAndView();
        mv.addObject("p",search);
        //mv.setViewName("/WEB-INF/jsp/contract.jsp");
        mv.setViewName("contract");
        return mv;
    }

//    @PostMapping("add")
//    public String add(@ModelAttribute Contract c) { //表单中的数据和Contract的一致
//       // ContextLoaderListener x=null;
//        System.out.println("新合同信息：" + c);
//        //SimpleDateFormat
//        //增加到数据库
//        int r=this.contractService.add(c);
////        if(5>3)
////            throw  new RuntimeException("xxxx");
//        if(r>0)
//            return "redirect:/contract/search";
//        return "forward:/addContract.jsp";
//    }
    @PostMapping("add")
    public String add(@Valid Contract c, @RequestParam(name = "hetong",required = false) MultipartFile hetong, HttpServletRequest request, BindingResult result) {
//        if(c.getBillno().length()<1){
//            //这个不能不填！
//            return "Fail";
//        }
        if(result.hasErrors()){

            return "error";
        }
        //表单中的数据和Contract的一致
        if(!hetong.isEmpty()){
            String oldName=hetong.getOriginalFilename();
            String picpath=request.getServletContext().getRealPath("images");
            File file=new File(picpath);
            if(!file.exists())
                file.mkdirs();
            //1:改名字,保留后缀
            //2:文件的路径，需要保存到数据库中。。。
            String suffix=oldName.substring(oldName.lastIndexOf('.'));
            if(!(suffix.equals(".jpg")||suffix.equals(".png"))){
                //throw new
                throw new RuntimeException("上传的文件不合法");
            }
            String newName= UUID.randomUUID()+suffix;
            try {
                hetong.transferTo(new File(file,newName));
                c.setHetongpic(newName);//设置上传的文件名
                System.out.println("新文件名："+newName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        int r=this.contractService.add(c);
        if(r>0)
            return "redirect:/contract/search";
        return "forward:/addContract.jsp";
    }
    @GetMapping("show")
    public String show(long id, Model m){
        Contract contract = this.contractService.find(id);
        m.addAttribute("contract",contract);
        return "showcontract";
    }
//    @GetMapping("show")
//    public String show(long id, HttpServletRequest request){
//        Contract contract = this.contractService.find(id);
//        request.setAttribute("contract",contract);
//    }

    //删除
    @GetMapping("del-{id}")
    public String del(@PathVariable("id") long id, RedirectAttributes rd){
        this.contractService.del(id);
        //httpsession,setMsg
        //remove
        rd.addFlashAttribute("msg","删除成功");
        //session中,重定向，显示一次，就会被删除！
        return  "redirect:/contract/search";
        // return "forward:/hello.jsp";
    }

    //加一个数据转换的注解
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        // true:允许输入空值，false:不能为空值 }

    }
    @ExceptionHandler//只能处理 ContractController的异常！
    public String exceptionHandler(Exception e){
        e.printStackTrace();
        return "fail";
    }
}